import Vue from 'vue'
import Vuex from 'vuex'
import api from '@/api/index.js';
import util from '@/common/util.js';

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		hasLogin: false, //用户是否登录  
		userInfo: {},
		isReloadWin: false,// 是否刷新
		overClient: 0 // 是否有超七天客户 1是 0否
	},
	getters: {
		/* 获取用户信息 */
		getUserInfo(state, getters) {
			return state.userInfo || {}
		}
	},
	actions: {
		updateReload({commit}, provider) {
			commit('UPDATERELOAD', provider)
		},
		// 更新是否有超过7天未联系的客户
		upateOverClient({
			state,
			commit
		}, provider) {
			commit('UPDATEOVERCLIENT', provider)
		},
		login({
			state,
			commit
		}, provider) {
			return new Promise((resolve, reject) => {
				api.doLogin(provider).then(res => {
					if (res.code == 200) {
						if (res.data.token) {
							commit('setUserInfo', res.data)
							commit('SETTOKEN', res.data.token)
						}
					} else {
						state.hasLogin = false;
					}
					resolve(res)
				}).catch(err => {
					reject(error)
				})
			})
		},
		logout({commit}) {
			commit('LOGOUT')
		},
		getUserInfoStore({
			state,
			commit
		}) {
			return new Promise((resolve, reject) => {
				api.getUserInfo().then(res => {
					if (res.code == 200) {
						commit('setUserInfo', res.data)
					} else {
						state.hasLogin = false;
						// 从本地缓存中异步移除指定key
						uni.removeStorageSync('kh:userInfo');
						uni.removeStorageSync('kh:token');
					}
					resolve(res)
				}).catch(err => {
					reject(err)
				})
			})
		},
	},
	mutations: {
		UPDATERELOAD(state, provider) { //改变是否刷新状态
			state.isReloadWin = provider;
		},
		SETTOKEN(state, provider) { //改变登录状态
			state.token = provider;
			uni.setStorage({ //将用户信息保存在本地  
				key: 'kh:token',
				data: provider
			})
		},
		setUserInfo(state, provider) {
			state.userInfo = provider;
			state.hasLogin = true; // 登录状态强制 开启
			uni.setStorage({ //将用户信息保存在本地
				key: 'kh:userInfo',
				data: state.userInfo
			})
		},
		LOGOUT(state) { //退出登录  
			state.hasLogin = false
			state.userInfo = {}
			uni.removeStorage({
				key: 'kh:userInfo'
			})
			uni.removeStorage({
				key: 'kh:token'
			})
		},
		UPDATEOVERCLIENT(state, provider) {
			state.overClient = provider;
		}
	}
})

export default store